# -*- coding: utf-8 -*-
"""
实名认证分发系统 - Python SDK
版本: 1.0.0

使用方法:
    from auth_sdk import AuthSDK
    sdk = AuthSDK('https://your-domain.com', 'YOUR_APP_ID', 'YOUR_APP_KEY')
    result = sdk.idcard_verify('张三', '110101199001011234')
    print(result)
"""
import hashlib
import time
import urllib.parse
import urllib.request
import json


class AuthSDK:
    def __init__(self, api_url, app_id, app_key):
        self.api_url = api_url.rstrip('/')
        self.app_id = app_id
        self.app_key = app_key

    def sign(self, params):
        keys = sorted(params.keys())
        s = ''
        for k in keys:
            if k != 'sign' and params[k] != '':
                s += f'{k}={params[k]}&'
        s += f'app_key={self.app_key}'
        return hashlib.md5(s.encode()).hexdigest()

    def get_balance(self):
        return self.request('/api/balance')

    def idcard_verify(self, name, idcard):
        params = {
            'name': name,
            'idcard': idcard,
            'app_id': self.app_id,
            'timestamp': int(time.time()),
        }
        params['sign'] = self.sign(params)
        return self.request('/api/idcard', params)

    def face_verify(self, image_base64, name, idcard):
        params = {
            'image_base64': image_base64,
            'name': name,
            'idcard': idcard,
            'app_id': self.app_id,
            'timestamp': int(time.time()),
        }
        params['sign'] = self.sign(params)
        return self.request('/api/face', params)

    def phone_verify(self, name, idcard, phone):
        params = {
            'name': name,
            'idcard': idcard,
            'phone': phone,
            'app_id': self.app_id,
            'timestamp': int(time.time()),
        }
        params['sign'] = self.sign(params)
        return self.request('/api/phone', params)

    def request(self, path, params=None):
        if params is None:
            params = {}
        url = self.api_url + path
        data = urllib.parse.urlencode(params).encode('utf-8')
        req = urllib.request.Request(
            url,
            data=data,
            headers={'Content-Type': 'application/x-www-form-urlencoded'}
        )
        try:
            with urllib.request.urlopen(req, timeout=30) as resp:
                return json.loads(resp.read().decode('utf-8'))
        except Exception as e:
            return {'code': -1, 'msg': str(e)}
